package com.qyhl.module_practice.activity.detail.apply;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.qyhl.module_practice.R;
import com.qyhl.module_practice.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.LoadingDialog;
import com.qyhl.webtv.basiclib.utils.dialog.OtherDialog;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.UpTokenBean;
import com.qyhl.webtv.commonlib.entity.act.UploadBean;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeAcitivityBean;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.ninephotolayout.BGASortableNinePhotoLayout;
import com.qyhl.webtv.commonlib.utils.qiniu.QiniuUpload;
import com.qyhl.webtv.commonlib.utils.qiniu.UploadResultListener;
import com.qyhl.webtv.commonlib.utils.view.imagebrowser.MNImageBrowser;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;

@Route(path = ARouterPathConstant.PRACTICE_APPLY)
public class PracticeActApplyActivity extends BaseActivity implements PracticeActApplyContract.PracticeActApplyView, BGASortableNinePhotoLayout.Delegate {
    @BindView(R2.id.upload_btn)
    TextView uploadBtn;
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.summary)
    EditText summary;
    @BindView(R2.id.NinePhotoLayout)
    BGASortableNinePhotoLayout NinePhotoLayout;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;

    /**
     * 上传token
     */
    private UpTokenBean mUpToken;
    /**
     * 图片多选
     */
    public static final int CHOOSE_REQUEST = 200;

    /**
     * 图片数据
     */
    private List<LocalMedia> selectedList = new ArrayList<>();


    private PracticeActApplyPresenter mPresenter;

    private LoadingDialog.Builder builder;

    private String upSummary;
    private String actId;
    private String volId;
    private String creator;

    private boolean hasAct = false;

    private List<PracticeAcitivityBean> mDataList = new ArrayList<>();

    private CommonAdapter commonAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getContentView() {
        return R.layout.practice_activity_act_apply;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new PracticeActApplyPresenter(this);
        actId = getIntent().getStringExtra("id");
        creator = getIntent().getStringExtra("userName");
        volId = getIntent().getStringExtra("volId");
        initView();

    }

    private void initView() {
        if (StringUtils.isEmpty(actId)) {
            loadMask.setVisibility(View.VISIBLE);
            loadMask.setStatus(LoadingLayout.Loading);
            mPresenter.getActList(volId);
            title.setText("服务上传");
            hasAct = true;

            recycleView.setLayoutManager(new LinearLayoutManager(this));
            recycleView.setAdapter(commonAdapter = new CommonAdapter<PracticeAcitivityBean>(this, R.layout.practice_item_act_apply, mDataList) {
                @Override
                protected void convert(ViewHolder holder, PracticeAcitivityBean bean, int position) {
                    holder.setText(R.id.title, bean.getName());

                    if (bean.isSelected()) {
                        holder.setImageResource(R.id.select, R.drawable.practice_search_org_on);
                    } else {
                        holder.setImageResource(R.id.select, R.drawable.practice_search_org_off);
                    }
                }
            });

            commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                    for (int i = 0; i < mDataList.size(); i++) {
                        if (i == position) {
                            mDataList.get(i).setSelected(true);
                        } else {
                            mDataList.get(i).setSelected(false);
                        }
                    }
                    commonAdapter.notifyDataSetChanged();
                }

                @Override
                public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                    return false;
                }
            });

        } else {
            loadMask.setVisibility(View.GONE);
            loadMask.setStatus(LoadingLayout.Success);
            title.setText("上传活动照片");
            hasAct = false;
        }

        builder = new LoadingDialog.Builder(PracticeActApplyActivity.this);
        builder.setTitle("提交中...");
        builder.setCanceledOnTouchOutside(false);
        builder.setCancelable(true);

        //九宫格设置监听
        NinePhotoLayout.setDelegate(this);
    }


    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(v -> {
            loadMask.setReloadButtonText("加载中...");
            mPresenter.getActList(volId);
        });

        summary.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (StringUtils.isNotEmpty(s.toString())) {
                    uploadBtn.setEnabled(true);
                } else {
                    uploadBtn.setEnabled(false);
                }
            }
        });
    }

    @OnClick({R2.id.back_btn, R2.id.upload_btn})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.back_btn) {
            finish();
        } else if (id == R.id.upload_btn) {
            new OtherDialog.Builder(PracticeActApplyActivity.this)
                    .setContentView(R.layout.practice_apply_dialog)
                    .setDismissButton(R.id.cancel_btn)
                    .setOnClickListener(R.id.commit_btn, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            checkData();
                        }
                    }).show();
        }
    }

    /**
     * 检测数据
     */
    private void checkData() {
        builder.show();

        if (!CommonUtils.getInstance().getUserCheck().equals("1") && CommonUtils.getInstance().getSite() == 217) {
            showToast("用户信息审核中，暂时无法使用该功能！", INFO);
            builder.dismiss();
            return;
        }

        if (hasAct) {
            for (int i = 0; i < mDataList.size(); i++) {
                if (mDataList.get(i).isSelected()) {
                    actId = mDataList.get(i).getId() + "";
                }
            }

            if (StringUtils.isEmpty(actId)) {
                showToast("请选择活动", 4);
                builder.dismiss();
                return;
            }
        }

        upSummary = summary.getText().toString();
        if (StringUtils.isEmpty(upSummary)) {
            showToast("请填写描述！", 4);
            builder.dismiss();
            return;
        }

        if (selectedList != null && selectedList.size() > 0) {
            if (mUpToken == null) {
                mPresenter.getToken(true);
                return;
            }
            List<UploadBean> uploadBeans = new ArrayList<UploadBean>();
            for (int i = 0; i < selectedList.size(); i++) {
                LocalMedia image = selectedList.get(i);
                UploadBean videoCoverBean = new UploadBean();
                videoCoverBean.setType(2);
                videoCoverBean.setPath(image.getCompressPath());
                videoCoverBean.setPostion(0);
                uploadBeans.add(videoCoverBean);
            }
            QiniuUpload.getQiniuUpload().UploadFiles(uploadBeans, mUpToken.getUptoken(), mUpToken.getPrefix(), new UploadResultListener() {
                @Override
                public void uplaodError() {
                    builder.dismiss();
                    showToast("上传图片出错", INFO);
                }

                @Override
                public void uploadSuccess(List<UploadBean> files) {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < files.size(); i++) {
                        if (i == files.size() - 1) {
                            stringBuilder.append(files.get(i).getUrl());
                        } else {
                            stringBuilder.append(files.get(i).getUrl()).append(",");
                        }
                    }

                    mPresenter.applyScore(volId, "", upSummary, actId, creator, stringBuilder.toString());

                }

                @Override
                public void uploadPre(double percent) {

                }
            });
        } else {
            builder.dismiss();
            showToast("请选择上传的图片", 4);
        }


    }


    @Override
    public void setActList(List<PracticeAcitivityBean> beanList) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");

        mDataList.clear();
        mDataList.addAll(beanList);
        commonAdapter.notifyDataSetChanged();

    }

    @Override
    public void actListError(String msg) {
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setReloadButtonText("点击重试~");
        loadMask.setErrorText(msg);
        if (msg.contains("暂无")) {
            loadMask.setErrorImage(R.drawable.empty_content);
        } else {
            loadMask.setErrorImage(R.drawable.error_content);
        }
    }

    @Override
    public void applySuccess(String msg) {
        builder.dismiss();
        showToast(msg, 4);
        BusFactory.getBus().post(new Event.PracticeActRefresh(0));
        finish();
    }

    @Override
    public void applyError(String msg) {
        builder.dismiss();
        showToast(msg, 4);
    }

    @Override
    public void getTokenSuccess(UpTokenBean data, boolean isUpload) {
        mUpToken = data;
        if (isUpload) {
            checkData();
        }
    }

    @Override
    public void getTokenError(boolean isUpload) {
        if (isUpload) {
            builder.dismiss();
            Toasty.normal(this, "上传失败！").show();
        }
    }

    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
        PictureSelector.create(PracticeActApplyActivity.this)
                //仅图片
                .openGallery(PictureMimeType.ofImage())
                //每行显示4张
                .imageSpanCount(4)
                .maxSelectNum(9)
                .selectionMode(PictureConfig.MULTIPLE)
                //允许使用相机
                .isCamera(true)
                //允许预览图片
                .previewImage(true)
                .isZoomAnim(true)
                .compress(true)
                .selectionMedia(selectedList)
                // 小于100kb的图片不压缩
                .minimumCompressSize(100)
                .forResult(CHOOSE_REQUEST);
    }

    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        for (int i = 0; i < selectedList.size(); i++) {
            if (selectedList.get(i).getCompressPath().equals(NinePhotoLayout.getData().get(position))) {
                selectedList.remove(i);
            }
        }

        NinePhotoLayout.removeItem(position);
    }

    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        MNImageBrowser.showImageBrowser(this, view, position, models);
    }

    @Override
    public void onNinePhotoItemExchanged(BGASortableNinePhotoLayout sortableNinePhotoLayout, int fromPosition, int toPosition, ArrayList<String> models) {

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<LocalMedia> resultList;
        if (requestCode == CHOOSE_REQUEST) {
            resultList = PictureSelector.obtainMultipleResult(data);
            if (resultList != null && resultList.size() > 0) {
                selectedList.clear();
                selectedList.addAll(resultList);
            }
            ArrayList<String> select = new ArrayList<>();

            for (int i = 0; i < selectedList.size(); i++) {
                select.add(selectedList.get(i).getCompressPath());
            }

            NinePhotoLayout.setData(select);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        ActionLogUtils.getInstance().onResume(this, ActionConstant.PRACTICE_APPLY);
    }

    @Override
    protected void onPause() {
        super.onPause();
        ActionLogUtils.getInstance().onPause(this, ActionConstant.PRACTICE_APPLY);
    }
}
